#include <xbook/initcall.h>
#include <xbook/debug.h>
#include <i386/io.h>
#include <platform/interrupt.h>

#define PORT_KEYDAT 0x60
#define PORT_KEYSTA 0x64
#define PORT_KEYCMD 0x64
#define KEYSTA_SEND_NOREADY 0x02
#define KEYCMD_WRITE_MODE 0x60
#define KBC_MODE 0x47

#define KEYCMD_SENDTO_MOUSE 0xd4
#define MOUSECMD_ENABLE 0Xf4

static void wait_KBC_sendready(void)
{
    while (1)
    {
        if ((in8(PORT_KEYSTA) & KEYSTA_SEND_NOREADY) == 0) {
            break;
        }
    }
}

static int mouse_handler(unsigned long irq, unsigned long arg)
{
    //printk("mouse handler!\n");
    unsigned char data;
    data = in8(PORT_KEYDAT);
    printk("data:%x %d\n", data, data);
    return 0;
}

void init_keyboard(void)
{
    wait_KBC_sendready();
    out8(PORT_KEYCMD, KEYCMD_WRITE_MODE);
    wait_KBC_sendready();
    out8(PORT_KEYDAT, KBC_MODE);
}

void enable_mouse(void)
{
    wait_KBC_sendready();
    out8(PORT_KEYCMD, KEYCMD_SENDTO_MOUSE);

    wait_KBC_sendready();
    out8(PORT_KEYCMD, 0xff);
    wait_KBC_sendready();
    out8(PORT_KEYCMD, 0xf5);
    
    wait_KBC_sendready();
    out8(PORT_KEYDAT, MOUSECMD_ENABLE);
}

static __init void ps2mouse_driver_init(void)
{
    printk("mouse driver init\n");
    init_keyboard();
    enable_mouse();
    register_irq(12, mouse_handler, 0, "mouse", "ps2mouse", 0);
}

static __exit void ps2mouse_driver_exit(void)
{
    printk("mouse driver exit\n");
}

driver_initcall(ps2mouse_driver_init);
driver_exitcall(ps2mouse_driver_exit);